<?php

/**
 * member actions.
 *
 * @package    sf_sandbox
 * @subpackage member
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class memberActions extends sfActions
{
    public function executeIndex()
    {
        return $this->redirect('member/memberList');
    }

    public function executeContactUsList()
    {
        $this->cms_contact_uss = CmsContactUsPeer::doSelect(new Criteria());
    }

    public function executeContactUsCreate()
    {
        $this->cms_contact_us = new CmsContactUs();

        $this->setTemplate('contactUsEdit');
    }

    public function executeContactUsEdit()
    {
        $this->cms_contact_us = CmsContactUsPeer::retrieveByPk($this->getRequestParameter('contact_id'));
        $this->forward404Unless($this->cms_contact_us);
    }

    public function executeContactUsUpdate()
    {
        if (!$this->getRequestParameter('contact_id')) {
            $cms_contact_us = new CmsContactUs();
        }
        else
        {
            $cms_contact_us = CmsContactUsPeer::retrieveByPk($this->getRequestParameter('contact_id'));
            $this->forward404Unless($cms_contact_us);
        }

        $cms_contact_us->setFullName($this->getRequestParameter('full_name'));
        $cms_contact_us->setEmail($this->getRequestParameter('email'));
        $cms_contact_us->setMessage($this->getRequestParameter('message'));
        $cms_contact_us->setStatusCode($this->getRequestParameter('status_code'));
        $cms_contact_us->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $cms_contact_us->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));

        $cms_contact_us->save();

        $this->setFlash('successMsg', "Update successfully");
        return $this->redirect('member/contactUsEdit?contact_id=' . $cms_contact_us->getContactId());
    }

    public function executeContactUsJsonList()
    {
        $sColumns = $this->getRequestParameter('sColumns');
        $aColumns = explode(",", $sColumns);

        $iColumns = $this->getRequestParameter('iColumns');

        $offset = $this->getRequestParameter('iDisplayStart');
        $sEcho = $this->getRequestParameter('sEcho');
        $limit = $this->getRequestParameter('iDisplayLength');
        $arr = array();
        $sql = " FROM cms_contact_us ";

        /******   total records  *******/
        $sWhere = " WHERE status_code = '" . Globals::STATUS_ACTIVE . "' ";
        $totalRecords = $this->getTotalRecords($sql . $sWhere);

        /******   total filtered records  *******/
        /*if ($this->getRequestParameter('filterUsername') != "") {
            $sWhere .= " AND dist.distributor_code LIKE '%" . mysql_real_escape_string($this->getRequestParameter('filterUsername')) . "%'";
        }*/
        $totalFilteredRecords = $this->getTotalRecords($sql . $sWhere);

        /******   sorting  *******/
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($this->getRequestParameter('iSortingCols')); $i++)
        {
            if ($this->getRequestParameter('bSortable_' . intval($this->getRequestParameter('iSortCol_' . $i))) == "true") {
                $sOrder .= $aColumns[intval($this->getRequestParameter('iSortCol_' . $i))] . "
                    " . mysql_real_escape_string($this->getRequestParameter('sSortDir_' . $i)) . ", ";
            }
        }

        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY") {
            $sOrder = "";
        }
        //var_dump($sOrder);
        /******   pagination  *******/
        $sLimit = " LIMIT " . mysql_real_escape_string($offset) . ", " . mysql_real_escape_string($limit);

        $query = "SELECT " . $sColumns . " " . $sql . " " . $sWhere . " " . $sOrder . " " . $sLimit;
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        while ($resultset->next())
        {
            $resultArr = $resultset->getRow();
            $distId = $resultArr['contact_id'] == null ? "" : $resultArr['contact_id'];

            $arr[] = array(
                $distId,
                $resultArr['full_name'] == null ? "" : $resultArr['full_name'],
                $resultArr['email'] == null ? "" : $resultArr['email'],
                $resultArr['message'] == null ? "" : $resultArr['message'],
                $resultArr['status_code'] == null ? "" : $resultArr['status_code'],
                $resultArr['created_on'] == null ? "" : $resultArr['created_on'],
            );
        }
        $output = array(
            "sEcho" => intval($sEcho),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalFilteredRecords,
            "aaData" => $arr
        );
        echo json_encode($output);

        return sfView::HEADER_ONLY;
    }

    public function executeMemberOrderJsonList()
    {
        $sColumns = $this->getRequestParameter('sColumns');
        $aColumns = explode(",", $sColumns);

        $iColumns = $this->getRequestParameter('iColumns');

        $offset = $this->getRequestParameter('iDisplayStart');
        $sEcho = $this->getRequestParameter('sEcho');
        $limit = $this->getRequestParameter('iDisplayLength');
        $arr = array();
        $sql = " FROM cms_member_order memberOrder
        LEFT JOIN cms_member member ON member.member_id = memberOrder.member_id ";

        /******   total records  *******/
        $sWhere = " WHERE memberOrder.status_code = '" . Globals::ORDER_STATUS_PENDING . "' ";
        $totalRecords = $this->getTotalRecords($sql . $sWhere);

        /******   total filtered records  *******/
        /*if ($this->getRequestParameter('filterUsername') != "") {
            $sWhere .= " AND dist.distributor_code LIKE '%" . mysql_real_escape_string($this->getRequestParameter('filterUsername')) . "%'";
        }*/
        $totalFilteredRecords = $this->getTotalRecords($sql . $sWhere);

        /******   sorting  *******/
        $sOrder = "ORDER BY  ";
        for ($i = 0; $i < intval($this->getRequestParameter('iSortingCols')); $i++)
        {
            if ($this->getRequestParameter('bSortable_' . intval($this->getRequestParameter('iSortCol_' . $i))) == "true") {
                $sOrder .= $aColumns[intval($this->getRequestParameter('iSortCol_' . $i))] . "
                    " . mysql_real_escape_string($this->getRequestParameter('sSortDir_' . $i)) . ", ";
            }
        }

        $sOrder = substr_replace($sOrder, "", -2);
        if ($sOrder == "ORDER BY") {
            $sOrder = "";
        }
        //var_dump($sOrder);
        /******   pagination  *******/
        $sLimit = " LIMIT " . mysql_real_escape_string($offset) . ", " . mysql_real_escape_string($limit);

        $query = "SELECT " . $sColumns . " " . $sql . " " . $sWhere . " " . $sOrder . " " . $sLimit;
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        while ($resultset->next())
        {
            $resultArr = $resultset->getRow();
            $distId = $resultArr['order_id'] == null ? "" : $resultArr['order_id'];

            $arr[] = array(
                $distId,
                $resultArr['fullname'] == null ? "" : $resultArr['fullname'],
                $resultArr['payment_method'] == null ? "" : $resultArr['payment_method'],
                $resultArr['total_amount'] == null ? "" : $resultArr['total_amount'],
                $resultArr['created_on'] == null ? "" : $resultArr['created_on'],
            );
        }
        $output = array(
            "sEcho" => intval($sEcho),
            "iTotalRecords" => $totalRecords,
            "iTotalDisplayRecords" => $totalFilteredRecords,
            "aaData" => $arr
        );
        echo json_encode($output);

        return sfView::HEADER_ONLY;
    }

    /* ****************************
     *      Member list
     * **************************** */
    public function executeMemberList()
    {
        $this->cms_members = CmsMemberPeer::doSelect(new Criteria());
    }

    public function executeMemberCreate()
    {
        $this->cms_member = new CmsMember();

        $this->setTemplate('memberEdit');
    }

    public function executeMemberEdit()
    {
        $this->cms_member = CmsMemberPeer::retrieveByPk($this->getRequestParameter('member_id'));
        $this->forward404Unless($this->cms_member);
    }

    public function executeMemberUpdate()
    {
        if (!$this->getRequestParameter('member_id')) {
            $cms_member = new CmsMember();
        }
        else
        {
            $cms_member = CmsMemberPeer::retrieveByPk($this->getRequestParameter('member_id'));
            $this->forward404Unless($cms_member);
        }

        $cms_member->setCompanyName($this->getRequestParameter('company_name'));
        $cms_member->setFullname($this->getRequestParameter('fullname'));
        $cms_member->setNric($this->getRequestParameter('nric'));
        $cms_member->setEmail($this->getRequestParameter('email'));
        $cms_member->setContact($this->getRequestParameter('contact'));
        $cms_member->setFax($this->getRequestParameter('fax'));
        $cms_member->setGender($this->getRequestParameter('gender'));
        if ($this->getRequestParameter('dob')) {
            list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());
            $cms_member->setDob("$y-$m-$d");
        }
        $cms_member->setSubscribeNewsletter($this->getRequestParameter('subscribe_newsletter'));
        $cms_member->setBankName($this->getRequestParameter('bank_name'));
        $cms_member->setBankAccNo($this->getRequestParameter('bank_acc_no'));
        $cms_member->setBankHolderName($this->getRequestParameter('bank_holder_name'));
        $cms_member->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $cms_member->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));

        $cms_member->save();

        $this->setFlash('successMsg', "Update successfully");
        return $this->redirect('member/memberEdit?member_id=' . $cms_member->getMemberId());
    }

    /* ****************************
     *      Member Order list
     * **************************** */
    public function executeOrderList()
    {
        $this->cms_member_orders = CmsMemberOrderPeer::doSelect(new Criteria());
    }

    public function executeOrderCreate()
    {
        $this->cms_member_order = new CmsMemberOrder();

        $this->setTemplate('edit');
    }

    public function executeOrderEdit()
    {
        $this->cms_member_order = CmsMemberOrderPeer::retrieveByPk($this->getRequestParameter('order_id'));
        $this->forward404Unless($this->cms_member_order);

        $c = new Criteria();
        $c->add(CmsMemberOrderDetailPeer::ORDER_ID, $this->cms_member_order->getOrderId());
        $this->cms_member_order_details = CmsMemberOrderDetailPeer::doSelect($c);
    }

    public function executeOrderUpdate()
    {
        if (!$this->getRequestParameter('order_id')) {
            $cms_member_order = new CmsMemberOrder();
        }
        else
        {
            $cms_member_order = CmsMemberOrderPeer::retrieveByPk($this->getRequestParameter('order_id'));
            $this->forward404Unless($cms_member_order);
        }

        $cms_member_order->setDeliveryName($this->getRequestParameter('delivery_name'));
        $cms_member_order->setDeliveryComment($this->getRequestParameter('delivery_comment'));
        $cms_member_order->setPaymentMethod($this->getRequestParameter('payment_method'));
        $cms_member_order->setPaymentComment($this->getRequestParameter('payment_comment'));
        $cms_member_order->setSubAmount($this->getRequestParameter('sub_amount'));
        $cms_member_order->setDeliveryAmount($this->getRequestParameter('delivery_amount'));
        $cms_member_order->setTotalAmount($this->getRequestParameter('total_amount'));
        $cms_member_order->setCountry($this->getRequestParameter('country'));
        $cms_member_order->setCity($this->getRequestParameter('city'));
        $cms_member_order->setAddress1($this->getRequestParameter('address1'));
        $cms_member_order->setAddress2($this->getRequestParameter('address2'));
        $cms_member_order->setState($this->getRequestParameter('state'));
        $cms_member_order->setPostcode($this->getRequestParameter('postcode'));
        $cms_member_order->setRemarks($this->getRequestParameter('remarks'));
        $cms_member_order->setStatusCode($this->getRequestParameter('status_code'));
        $cms_member_order->setCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));
        $cms_member_order->setUpdatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID, Globals::SYSTEM_USER_ID));

        $cms_member_order->save();

        $c = new Criteria();
        $c->add(CmsMemberOrderDetailPeer::ORDER_ID, $cms_member_order->getOrderId());
        $cms_member_order_details = CmsMemberOrderDetailPeer::doSelect($c);
        foreach ($cms_member_order_details as $cms_member_order_detail):
            $cms_member_order_detail->setStatusCode($this->getRequestParameter('detail_status_code_'.$cms_member_order_detail->getDetailId()));
            $cms_member_order_detail->save();
        endforeach;

        $this->setFlash('successMsg', "Update successfully");
        return $this->redirect('member/orderEdit?order_id=' . $cms_member_order->getOrderId());
    }

    /* ****************************
  *      Function
  * **************************** */
    function getTotalRecords($sql)
    {
        $query = "SELECT COUNT(*) AS _TOTAL " . $sql;
        //var_dump($query);
        $connection = Propel::getConnection();
        $statement = $connection->prepareStatement($query);
        $resultset = $statement->executeQuery();

        $count = 0;
        if ($resultset->next()) {
            $arr = $resultset->getRow();
            if ($arr["_TOTAL"] != null) {
                $count = $arr["_TOTAL"];
            } else {
                $count = 0;
            }
        }
        return $count;
    }
}
